<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="父级分类" prop="fatherCategoryId">
        <el-select v-model="queryParams.fatherCategoryId" placeholder="请选择父级分类" clearable
          @change="onFatherCategoryChange">
          <el-option v-for="item in fatherCategoryOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择商品分类" clearable
          :disabled="!queryParams.fatherCategoryId">
          <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="库存数量" prop="stockRange">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-input v-model="queryParams.params.beginStock" placeholder="开始值" clearable
              @keyup.enter.native="handleQuery" />
          </el-col>
          <el-col :span="2" style="text-align: center; line-height: 40px;">-</el-col>
          <el-col :span="11">
            <el-input v-model="queryParams.params.endStock" placeholder="结束值" clearable
              @keyup.enter.native="handleQuery" />
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 商品已售区间查询 -->
      <el-form-item label="商品已售" prop="countRange">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-input v-model="queryParams.params.beginCount" placeholder="开始值" clearable
              @keyup.enter.native="handleQuery" />
          </el-col>
          <el-col :span="2" style="text-align: center; line-height: 40px;">-</el-col>
          <el-col :span="11">
            <el-input v-model="queryParams.params.endCount" placeholder="结束值" clearable
              @keyup.enter.native="handleQuery" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable>
          <el-option v-for="dict in dict.type.product_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:productinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['product:productinfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['product:productinfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:productinfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品id" align="center" prop="id" />
      <el-table-column label="分类id" align="center" prop="categoryId" />

      <el-table-column label="父级分类名" align="center">
        <template slot-scope="scope">
          {{ scope.row.parentCategory ? scope.row.parentCategory.name : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="分类名" align="center">
        <template slot-scope="scope">
          <!-- 先判断category是否存在，再访问name -->
          {{ scope.row.category ? scope.row.category.name : '-' }}
        </template>
      </el-table-column>




      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="副标题" align="center" prop="subtitle" />

      <!-- 主图URL -->
      <el-table-column label="主图URL" align="center" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.mainImage" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="库存数量" align="center" prop="stock" />
      <el-table-column label="商品已售" align="center" prop="count" />

      <!-- 商品状态 -->
      <el-table-column label="商品状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="商品详情描述" align="center" prop="description">
        <!-- 表格中展示富文本内容时使用v-html -->
        <template slot-scope="scope">
          <div v-html="scope.row.productDetail.description" class="rich-text-preview"></div>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['product:productinfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['product:productinfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="form.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="父级分类" prop="fatherCategoryId">
          <el-select v-model="form.fatherCategoryId" placeholder="请选择父级分类" clearable
            @change="onDialogFatherCategoryChange">
            <el-option v-for="item in fatherCategoryOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="子分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择子分类" clearable :disabled="!form.fatherCategoryId">
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="主图URL" prop="mainImage">
          <image-upload v-model="form.mainImage" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="商品已售" prop="count">
          <el-input v-model="form.count" placeholder="请输入商品已售" />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择商品状态">
            <el-option v-for="dict in dict.type.product_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listProductinfo,
    getProductinfo,
    delProductinfo,
    addProductinfo,
    updateProductinfo
  } from "@/api/product/productinfo"
  import {
    fatherListProductCategory,
    listProductCategory
  } from "@/api/product/category"
  export default {
    name: "Productinfo",
    dicts: ['product_status'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品表格数据
        productinfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        categoryOptions: [],
        fatherCategoryOptions: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fatherCategoryId: null, // 父级分类
          categoryId: null, // 子分类,
          name: null,
          stock: null,
          count: null,
          status: null,
          params: {
            beginStock: null, // 库存开始值
            endStock: null, // 库存结束值
            beginCount: null, // 已售开始值
            endCount: null // 已售结束值
          }
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          categoryId: [{
            required: true,
            message: "分类id不能为空",
            trigger: "change"
          }],
          name: [{
            required: true,
            message: "商品名称不能为空",
            trigger: "blur"
          }],
          mainImage: [{
            required: true,
            message: "主图URL不能为空",
            trigger: "blur"
          }],
          price: [{
            required: true,
            message: "价格不能为空",
            trigger: "blur"
          }],
          fatherCategoryId: [{
            required: true,
            message: "父级分类不能为空",
            trigger: "change"
          }],
          categoryId: [{
            required: true,
            message: "子分类不能为空",
            trigger: "change"
          }]
        }
      }
    },
    created() {
      this.getList()
      this.getFatherCategoryOptions();
    },
    methods: {
      /** 查询商品列表 */
      getList() {
        this.loading = true
        listProductinfo(this.queryParams).then(response => {
          this.productinfoList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          categoryId: null,

          name: null,
          subtitle: null,
          mainImage: null,
          price: null,
          stock: null,
          count: null,
          status: null,
          del: null
        }
        this.resetForm("form")
      },
      /** 搜索按钮操作 */
      handleQuery() {
        if (this.queryParams.params.beginStock && this.queryParams.params.endStock) {
          if (this.queryParams.params.beginStock > this.queryParams.params.endStock) {
            this.$message.warning("库存结束值必须大于开始值");
            return;
          }
        }
        if (this.queryParams.params.beginCount && this.queryParams.params.endCount) {
          if (this.queryParams.params.beginCount > this.queryParams.params.endCount) {
            this.$message.warning("已售结束值必须大于开始值");
            return;
          }
        }
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm")
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加商品"
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getProductinfo(id).then(response => {
          const data = response.data;

          // 映射数据到表单
          this.form = {
            ...data,
            fatherCategoryId: data.parentCategory ? data.parentCategory.id : null, // 父分类 ID
            categoryId: data.category ? data.category.id : null // 子分类 ID
          };

          // 打开弹窗
          this.open = true;
          this.title = "修改商品";

          // 加载子分类选项并回显
          if (this.form.fatherCategoryId) {
            listProductCategory({
              parentId: this.form.fatherCategoryId
            }).then(res => {
              this.categoryOptions = res.rows || [];
              // 确保子分类值在选项加载完成后赋值
              this.form.categoryId = data.category ? data.category.id : null;
            });
          } else {
            this.categoryOptions = [];
          }
        });
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateProductinfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addProductinfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function() {
          return delProductinfo(ids)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('product/productinfo/export', {
          ...this.queryParams
        }, `productinfo_${new Date().getTime()}.xlsx`)
      },
      getFatherCategoryOptions() {
        fatherListProductCategory().then(res => {
          this.fatherCategoryOptions = res.rows || [];
        });
      },
      onFatherCategoryChange(parentId) {
        this.queryParams.categoryId = null; // 清空子分类选择
        if (!parentId) {
          this.categoryOptions = [];
          return;
        }
        listProductCategory({
          parentId
        }).then(res => {
          this.categoryOptions = res.rows || [];
        });
      },
      onDialogFatherCategoryChange(parentId) {
        this.form.categoryId = null; // 清空子分类
        if (!parentId) {
          this.categoryOptions = [];
          return;
        }
        listProductCategory({
          parentId
        }).then(res => {
          this.categoryOptions = res.rows || [];
        });
      }

    }
  }
</script>

<style scoped>
  /* 富文本预览容器 */
  .rich-text-preview {
    max-width: 500px;
    padding: 5px;
    overflow: hidden;
  }

  /* 关键：使用深度选择器穿透 scoped 限制 */
  ::v-deep .rich-text-preview img {
    max-width: 100% !important;
    height: auto !important;
    max-height: 150px !important;
    object-fit: contain;
    /* 保持图片比例，不裁剪 */
    display: block;
    margin: 0 auto;
  }

  /* 处理可能的内联样式优先级问题 */
  ::v-deep .rich-text-preview img[style] {
    width: auto !important;
    /* 覆盖内联 width */
  }
</style>
